package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyFh;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMtsxf;
import cn.stylefeng.guns.sys.modular.system.entity.BtyYj;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyFhMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyYjMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMtsxfParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyYjParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMtsxfResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyYjResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyYjService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-10-22
 */
@Service
public class BtyYjServiceImpl extends ServiceImpl<BtyYjMapper, BtyYj> implements BtyYjService {
     @Resource
     private BtyFhMapper fhMapper;
    @Override
    public void add(BtyYjParam param){
        BtyYj entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyYjParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyYjParam param){
        BtyYj oldEntity = getOldEntity(param);
        BtyYj newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyYjResult findBySpec(BtyYjParam param){
        return null;
    }

    @Override
    public List<BtyYjResult> findListBySpec(BtyYjParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyYjParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 导入excel
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchImport(String fileName, MultipartFile file, BtyYjParam param){
        boolean notNull = false;
        try {
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //System.out.println("sheets:"+sheets);
            //导入之前删掉之前的数据
            baseMapper.delete(new QueryWrapper<>());
                 String yf=param.getZdrq();
                //第一个sheet
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
                    Cell cell = row.getCell(4);
                    if (ToolUtil.isNotEmpty(cell)) {
                        cell.setCellType(CellType.STRING);
                    }
                    //店名
                    String dm=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    //科目名称
                    String kmmc = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //客商辅助核算名称
                    String ksfzhs = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
                    //方向
                    String fx = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
                    //余额
                    String ye="";
                    if(ToolUtil.isEmpty(row.getCell(4).toString().trim())){
                       ye="0";
                    }else {
                       ye=row.getCell(4).getStringCellValue();
                    }

                    BtyYj yj=new BtyYj();
                    yj.setDm(dm);
                    yj.setKmmc(kmmc);
                    yj.setKsfzhs(ksfzhs);
                    yj.setFx(fx);
                    yj.setYe(new BigDecimal(ye));
                    baseMapper.insert(yj);
                }
                //excel导入成功之后获取押金总和明细保存到分红表中
               List<BtyYjResult>list=baseMapper.dmList();
            for (BtyYjResult result : list) {
                StringBuilder sb=new StringBuilder();
                String dm=result.getDm();
                BigDecimal ye=result.getYe();
                //根据店名查询对应的押金明细，逗号分隔拼接到一起
                BtyYjParam yjParam=new BtyYjParam();
                yjParam.setDm(dm);
                List<BtyYjResult>detailList=baseMapper.detailListByDm(yjParam);
                for (BtyYjResult detail : detailList) {
                    String bz=detail.getBz();
                    sb.append(bz).append(",");
                }
                String bz= DateUtil.comma(sb.toString());
                BtyFh fh=fhMapper.selectOne(new QueryWrapper<BtyFh>().eq("yf",yf).eq("dm",dm));
                if(ToolUtil.isNotEmpty(fh)){
                    fh.setYsyj(ye);
                    fh.setBz(bz);
                    fhMapper.updateById(fh);
                }
            }
        } catch (Exception e) {
            notNull=false;
            e.printStackTrace();
        }
        return notNull;
    }

    private Serializable getKey(BtyYjParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyYj getOldEntity(BtyYjParam param) {
        return this.getById(getKey(param));
    }

    private BtyYj getEntity(BtyYjParam param) {
        BtyYj entity = new BtyYj();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
